package com.yz.antlr.clr.main;

import com.yz.antlr.clr.g4.CalcLexer;
import com.yz.antlr.clr.g4.CalcParser;
import com.yz.antlr.clr.impstand.EvalVisitor;
import lombok.extern.log4j.Log4j;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.tree.ParseTree;



@Log4j
public class CalcTestMain {

	public static void main(String[] args) {
		String source = "1+(2*3^(2^2+1))";
        try {
        	
        	// 入力流れ
			CharStream input = CharStreams.fromString(source);
			
			// 词法分析
			CalcLexer lexer = new CalcLexer(input);
			
			// 文法分析
			CommonTokenStream tokens = new CommonTokenStream(lexer);
			CalcParser parser = new CalcParser(tokens);
			
			// AST
			ParseTree tree = parser.prog();
			
			// AST遍歴
			EvalVisitor eval = new EvalVisitor();
			Double result = eval.visit(tree);
			
			// 結果出力
			System.out.println(source + " = " + result);
			System.out.println(tree.toStringTree(parser));
			
		} catch (RecognitionException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

}
